#include "inventoryservice.h"
#include "inventorydao.h"
#include "productdao.h"
#include "stockindao.h"
#include "database.h"
#include <QDebug>

InventoryService::InventoryService(Database *db, QObject *parent)
    : QObject(parent)
{
    m_productDao = new ProductDAO(db);
    m_inventoryDao = new InventoryDAO(db);
    m_stockInDao = new StockInDAO(db);
}

QVector<QMap<QString, QVariant>> InventoryService::getAllCategories()
{
    return m_productDao->getAllCategories();
}

QVector<QMap<QString, QVariant>> InventoryService::getProductsByCategory(int categoryId)
{
    return m_productDao->getProductsByCategory(categoryId);
}

QMap<QString, QVariant> InventoryService::getProductDetails(int productId)
{
    return m_productDao->getProductById(productId);
}

int InventoryService::getCurrentStock(int productId)
{
    return m_inventoryDao->getCurrentStock(productId);
}

/**
 * 商品入库操作算法
 * 业务逻辑：使用数据库事务确保数据一致性
 * 处理流程：
 * 1. 开启数据库事务
 * 2. 添加入库记录到入库表
 * 3. 更新商品库存数量
 * 4. 提交事务（成功）或回滚事务（失败）
 * 
 * 异常处理：任何步骤失败都会回滚事务，确保数据完整性
 * 
 * @param productId 商品ID
 * @param quantity 入库数量
 * @param purchasePrice 采购价格
 * @param supplier 供应商
 * @param operatorId 操作员ID
 * @param note 备注信息
 * @return 入库操作是否成功
 */
bool InventoryService::stockIn(int productId, int quantity, double purchasePrice,
                              const QString &supplier, int operatorId, const QString &note)
{
    // 开始事务
    if (!m_stockInDao->beginTransaction()) {
        return false;
    }

    try {
        // 添加入库记录
        if (!m_stockInDao->addStockInRecord(productId, quantity, purchasePrice, supplier, operatorId, note)) {
            m_stockInDao->rollbackTransaction();
            return false;
        }

        // 更新库存
        if (!m_inventoryDao->increaseStock(productId, quantity)) {
            m_stockInDao->rollbackTransaction();
            return false;
        }

        // 提交事务
        if (!m_stockInDao->commitTransaction()) {
            m_stockInDao->rollbackTransaction();
            return false;
        }

        return true;
    } catch (...) {
        m_stockInDao->rollbackTransaction();
        return false;
    }
}

// 获取所有入库记录
QVector<QMap<QString, QVariant>> InventoryService::getAllStockInRecords()
{
    return m_stockInDao->getAllStockInRecords();
}

// 根据条件查询入库记录
QVector<QMap<QString, QVariant>> InventoryService::getStockInRecordsByCondition(
    const QString &startDate, const QString &endDate,
    int productId, const QString &supplier)
{
    return m_stockInDao->getStockInRecordsByCondition(startDate, endDate, productId, supplier);
}
